<template>
  <div class="add-wrapper">
    <el-page-header @back="goBack" :content="isAdd ? '创建生产' : '编辑生产'">
    </el-page-header>
    <div class="form-wrapper">
      <div class="top-form">
        <div class="descLabel">基本信息</div>
        <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          @submit.native.prevent
          label-width="120px"
        >
          <el-form-item v-if="!isAdd" prop="production_serial" label="生产单号">
            <el-input v-model="dataForm.production_serial" disabled></el-input>
          </el-form-item>
          <el-form-item prop="name" label="生产名称">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="bills_date" label="单据日期">
            <el-date-picker
              v-model="dataForm.bills_date"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            prop="order_name"
            label="销售订单"
            v-if="isAdd || (!isAdd && hasBindOrder)"
          >
            <el-select
              clearable
              v-model="dataForm.order_name"
              ref="choose"
              placeholder="请选择"
              :style="{ width: '100%' }"
              @change="(e) => handleChangeSelect(e)"
              @focus="handleTestTasks(2)"
              :disabled="(!isAdd && hasBindOrder) || useChecked"
            ></el-select>
            <el-checkbox
              v-model="useChecked"
              @change="handleChange"
              :disabled="(!isAdd && hasBindOrder) || useChecked"
              >不绑定销售订单</el-checkbox
            >
          </el-form-item>
          <el-form-item prop="customer_manager" label="负责人">
            <el-input v-model="dataForm.customer_manager"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              placeholder="请输入"
              type="textarea"
              :rows="3"
              v-model="dataForm.remarks"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="生产成品">
            <el-button type="primary" @click="handleAdd">添加</el-button>
            <el-button type="primary" @click="batchDelete">移除</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="size-form padTop20">
        <el-form @submit.native.prevent label-width="120px">
          <el-form-item label="">
            <!-- @selection-change="handleSelectionChange" -->
            <el-table
              :data="generateList"
              border
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column
                type="index"
                label="序号"
                header-align="center"
                align="center"
                width="80"
              ></el-table-column>
              <el-table-column
                prop="product_name"
                label="产品"
                header-align="center"
                align="center"
                width="360"
              >
                <template slot-scope="scope">
                  <div class="disCenter itemBox">
                    <div class="imgBox">
                      <img :src="scope.row.product_master_pic" />
                    </div>
                    <div class="rightBox">
                      <el-tooltip
                        class="item"
                        effect="light"
                        :content="scope.row.product_name"
                        placement="top"
                      >
                        <span class="top overTwoHidden">{{
                          scope.row.product_name
                        }}</span>
                      </el-tooltip>

                      <span class="bottom"
                        >产品编号: {{ scope.row.product_serial }}</span
                      >
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="sku_name"
                label="规格"
                header-align="center"
                align="center"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="sale_num"
                label="销售数量"
                header-align="center"
                align="center"
                v-if="hasBindOrder"
              ></el-table-column>
              <el-table-column
                prop="delivery_date"
                label="交付日期"
                header-align="center"
                align="center"
                width="150"
                v-if="hasBindOrder"
              ></el-table-column>
              <el-table-column
                label-class-name="thRequired"
                prop="planned_production"
                label="计划生产数量"
                header-align="center"
                align="center"
                width="200"
              >
                <template slot-scope="scope">
                  <el-input
                    type="number"
                    placeholder="请输入"
                    v-model="scope.row.planned_production"
                    :min="0"
                    @focus="handleFocus(scope.row)"
                    @blur="plannedBlur(scope)"
                  >
                  </el-input> </template
              ></el-table-column>
              <el-table-column
                prop="bom_name"
                label="BOM"
                header-align="center"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="principal"
                label="负责人"
                header-align="center"
                align="center"
                width="120"
              >
                <template slot-scope="scope">
                  <el-input placeholder="请输入" v-model="scope.row.principal">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="plan_start"
                label="计划开始日期"
                header-align="center"
                align="center"
                width="180"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.plan_start"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                prop="plan_end"
                label="计划结束日期"
                header-align="center"
                align="center"
                width="180"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.plan_end"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('handle')"
                fixed="right"
                header-align="center"
                align="center"
                width="150"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="toBom(scope)"
                    :disabled="!scope.row.hasFillDetail"
                    >BOM明细</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope.row)"
                    >移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <div style="margin-bottom: 36px">
            <div class="disCenter" style="justify-content: flex-end">
              <div style="margin-right: 64px">合计</div>
              <div style="margin-right: 36px">
                总数量： <span class="mainColor storngTip">{{ tipTotal }}</span>
              </div>
            </div>
          </div>
        </el-form>
        <div class="descMockBox" style="margin-top: 0px !important">
          <div class="descMockLabel" @click="handleClick">物料消耗</div>
          <el-table
            :data="tableData"
            :span-method="objectSpanMethod"
            border
            style="
              width: calc(100% - 120px);
              margin-top: 20px;
              margin-left: 120px;
            "
          >
            <el-table-column
              type="index"
              label="序号"
              header-align="center"
              align="center"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="supplier_name"
              label="执行单位"
              header-align="center"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="numCount"
              label="计划消耗数量"
              header-align="center"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="material_serial"
              label="物料编码"
              header-align="center"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="物料名称"
              header-align="center"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="specifications_model"
              label="规格型号"
              header-align="center"
              align="center"
            >
            </el-table-column>
          </el-table>
          <div style="margin: 21px 0 10px">
            <div class="disCenter" style="justify-content: flex-end">
              <div style="margin-right: 64px">合计</div>
              <div style="margin-right: 36px">
                总数量：
                <span class="mainColor storngTip">{{ customTotal }}</span>
              </div>
            </div>
          </div>
          <!-- <el-table
      :data="tableData"
      :span-method="objectSpanMethod"
      border
      :header-cell-style="{ textAlign: 'center', backgroundColor: '#F5F7FA' }"
    >
      <el-table-column prop="School" label="学校" align="center">
      </el-table-column>
      <el-table-column prop="Grade" label="年级" align="center" />
      <el-table-column prop="Class" label="班级" align="center" />
      <el-table-column prop="Name" label="姓名" align="center" />
      <el-table-column prop="Chinese" label="语文" align="center" />
      <el-table-column prop="Math" label="数学" align="center" />
      <el-table-column prop="English" label="英语" align="center" />
    </el-table> -->
        </div>
      </div>
      <div style="margin-bottom: 36px">
        <el-button @click="goBack" :style="`margin-left: 45%; margin-top: 36px`"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="dataFormSubmitHandle()"
          style="margin-left: 21px"
          >确定</el-button
        >
      </div>
    </div>
    <el-backtop></el-backtop>
    <el-dialog :visible.sync="dialogVisible" title="查看">
      <img width="100%" :src="dialogImageUrl" class="avatar" />
    </el-dialog>
    <ProductChoose
      v-if="addOrUpdateVisible"
      ref="orderProduct"
      @handleClose="handleClose"
      @handleConfirm="fitConfirm"
      :chooseData="generateList"
      :is_bom="true"
    ></ProductChoose>
    <OrderProductChoose
      v-if="productOrderVisible"
      ref="orderProduct"
      @orderProductClose="orderProductClose"
      @orderProductConfirm="orderProductConfirm"
      :chooseData="generateList"
      :orderProductData="orderProductData"
    ></OrderProductChoose>
    <OrderList
      v-if="orderVisible"
      ref="planOrder"
      @handleClose="handleOrderClose"
      @handleConfirm="orderConfirm"
      :chooseData="generateList"
      :is_bom="true"
    ></OrderList>
    <!-- generateList[currentIndex].bomRawSourceInner -->
    <BomDetail
      v-if="bomVisible"
      ref="bomRef"
      @handleClose="handleBomClose"
      @handleConfirm="bomConfirm"
      :bomRawSource="bomRawSource"
      :isAdd="isAdd"
    ></BomDetail>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
import _ from 'lodash'
import {
  getProductionDetail,
  addProduction,
  prodSubRemove,
  getOrderDetail,
  getBomDetail,
  getSupplierBomList,
} from "@/api";
import { formatDayTime } from "@/utils";
import ProductChoose from "@/components/product-choose";
import OrderProductChoose from "@/components/order-product-choose";
import OrderList from "./order-list";
import BomDetail from "./bom-detail";
export default {
  components: {
    ProductChoose,
    OrderList,
    OrderProductChoose,
    BomDetail,
  },
  data() {
    return {
      visible: false,
      dataForm: {
        id: "",
        name: "",
        bills_date: "",
        customer_manager: "",
        customer_name: "",
        order_id: "",
        order_name: "",
        remarks: "",
      },
      dialogImageUrl: "",
      dialogVisible: false,
      addOrUpdateVisible: false,
      generateList: [],
      isAdd: true,
      // 批量删除缓存数据
      subChooseInfo: [],
      tipTotal: "",
      orderVisible: false,
      hasBindOrder: false,
      bindOrderObj: {},
      productOrderVisible: false,
      // order 产品源数据  绑定销售订单 产品数据来源
      orderProductData: [],
      useChecked: false,
      bomVisible: false,
      // bomSubList: [],
      bomRawSource: {},
      // 查看bom 当前点击行所在信息
      currentProductSkuObj: {},
      currentIndex: null,
      tableData: [],
      // 编辑对比数据用
      oldInputData: null,
      colFields: [
        "index",
        "supplier_name",
        "numCount",
        "material_serial",
        "name",
        "specifications_model",
      ],

      spanArr: [], //存储合并单元格的开始位置
      customTotal: "",
    };
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: "必填项不能为空",
            trigger: "blur",
          },
        ],
        bills_date: [
          {
            required: true,
            message: "必填项不能为空",
            trigger: "change",
          },
        ],
      };
    },
  },
  activated() {
    let that = this;

    // console.log(this.$refs['dataForm'].fields)
    // if (this.$refs['dataForm'].fields) {
    //   this.$refs['dataForm'].resetFields()
    // }
    this.generateList = [];
    this.tableData = [];
    this.spanArr = [];
    this.isAdd = true;
    this.subChooseInfo = [];
    this.tipTotal = "";
    this.customTotal = "";
    this.currentProductSkuObj = {};
    this.currentIndex = null;
    this.oldInputData = null;
    this.spanArr = [];
    that.$refs["dataForm"].resetFields();
    const id = that.$route.params.id;
    that.dataForm.id = id;
    this.dataForm.bills_date = formatDayTime(new Date().getTime());
    this.hasBindOrder = false;
    if (id) {
      that.fetchDetail(id);
      that.isAdd = false;
      that.bindOrderObj = {};
    }
  },
  watch: {
    generateList: {
      handler() {
        this.calcTotal();
      },
      deep: true,
      immediate: true,
    },
    tableData: {
      handler() {
        this.calcCustomTotal();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleChangeSelect(val) {
      console.log(val);
      if (!val) {
        this.generateList = [];
      }
    },
    transBomCustomList() {
      console.log(this.generateList);
      // 删除未绑定数据
      const list = this.generateList.filter(
        (item) => item?.bomRawSourceInner?.fill_bom_sub
      );
      if (list.length > 0) {
        let temp = [];
        for (let i = 0; i < list.length; i++) {
          let arr = [];
          let bom_sub_list = list[i].bomRawSourceInner.bom_sub;
          bom_sub_list.forEach((item) =>
            arr.push({
              material_serial: item.material_serial,
              name: item.name,
              specifications_model: item.specifications_model,
            })
          );

          let fill_bom_sub_list = list[i].bomRawSourceInner.fill_bom_sub;
          fill_bom_sub_list.forEach((it, idx) => {
            let info = arr[idx];
            console.log(it);
            let fitList = it?.supplyList ? it.supplyList : it?.execute_list;
            // 编辑回显区分
            let key = it?.supplyList ? "id" : "supplier_id";
            fitList &&
              fitList.forEach((itS) => {
                temp.push({
                  supplier_id: itS?.supplier_id || itS?.id,
                  num: Number(itS.num),
                  supplier_name: itS?.name || itS?.supplier_name,
                  ...info,
                });
              });
          });
        }
        console.log(temp);
        const filterList = temp.filter((item) => item.num > 0);
        // 供应商 id 去重
        let tempIds = [];
        filterList.forEach((item) => {
          tempIds.push(item.supplier_id);
        });

        let combineObj = {};
        const unique = [...new Set(tempIds)];
        // debugger;
        console.log(filterList);
        for (let i = 0; i < unique.length; i++) {
          // 当前id匹配项
          let targetList = filterList.filter(
            (item) => item.supplier_id === unique[i]
          );
          let count = targetList.reduce((pre, cur) => {
            return pre + Number(cur.num);
          }, 0);
          targetList.forEach((item) => (item.numCount = count));
          combineObj[i] = targetList;
        }

        let sortList = [];
        for (let key in combineObj) {
          sortList = [...sortList, ...combineObj[key]];
        }
        console.log(combineObj);
        console.log(sortList);
        this.tableData = sortList;
        this.getSpanArr();
      } else {
        this.tableData = [];
        this.getSpanArr();
      }
    },
    getSpanArr() {
      for (let i = 0; i < this.tableData.length; i++) {
        let row = i;
        // let col = i % this.colCount;
        if (row === 0) {
          // i 表示行 j表示列
          for (let j = 0; j < this.colFields.length; j++) {
            this.spanArr[i * this.colFields.length + j] = {
              rowspan: 1,
              colspan: 1,
            };
          }
        } else {
          for (let j = 0; j < this.colFields.length; j++) {
            // 当前和上一次的一样
            //  合并所有列的相同数据单元格
            if (
              this.colFields[j] === "supplier_name" ||
              this.colFields[j] === "numCount"
            ) {
              // 指定合并哪些列

              if (
                this.tableData[row]["supplier_name"] !==
                this.tableData[row - 1]["supplier_name"]
              ) {
                // 哪些不合并:School不一样的,不合并
                this.spanArr[row * this.colFields.length + j] = {
                  rowspan: 1,
                  colspan: 1,
                };
              } else if (
                this.tableData[row][this.colFields[j]] ===
                this.tableData[row - 1][this.colFields[j]]
              ) {
                let beforeItem =
                  this.spanArr[(row - 1) * this.colFields.length + j];
                this.spanArr[row * this.colFields.length + j] = {
                  rowspan: 1 + beforeItem.rowspan, // 合并几列
                  colspan: 1, // 合并几行
                };
                beforeItem.rowspan = 0;
                beforeItem.colspan = 0;
              } else {
                // rowspan 和 colspan 都为1表格此单元格不合并
                this.spanArr[row * this.colFields.length + j] = {
                  rowspan: 1,
                  colspan: 1,
                };
              }
            }
          }
        }
      }
      // 对数据进行倒序
      let stack = [];

      for (let i = 0; i < this.colFields.length; i++) {
        for (let j = 0; j < this.tableData.length; j++) {
          // console.log("i=" + i + " j=" + j);
          // i 表示列 j表示行
          if (j === 0) {
            if (this.spanArr[j * this.colFields.length + i]?.rowspan === 0) {
              stack.push(this.spanArr[j * this.colFields.length + i]);
            }
          } else {
            if (this.spanArr[j * this.colFields.length + i]?.rowspan === 0) {
              stack.push(this.spanArr[j * this.colFields.length + i]);
            } else {
              stack.push(this.spanArr[j * this.colFields.length + i]);
              while (stack.length > 0) {
                let pop = stack.pop();
                let len = stack.length;
                this.spanArr[(j - len) * this.colFields.length + i] = pop;
              }
            }
          }
        }
      }
    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      return this.spanArr[rowIndex * this.colFields.length + columnIndex];
    },

    handleFocus(row) {
      this.oldInputData = row.planned_production;
    },
    plannedBlur(scope) {
      let index = scope.$index;
      let row = scope.row;
      this.currentProductSkuObj = row;
      console.log(row);
      console.log(this.generateList);
      // planned_production未变更

      // 为0或未赋值，清空绑定数据
      if (!Number(row.planned_production)) {
        delete row.bomRawSourceInner;
        row.hasFillDetail = false;
        console.log(this.generateList);
        return;
      }
      // planned_production已查询接口 数据再变更
      if (
        this.oldInputData !== row.planned_production &&
        row?.bomRawSourceInner
      ) {
        const planned_production = row.planned_production;
        let bom_sub = row.bomRawSourceInner.bom_sub;
        bom_sub.forEach((item) => {
          item.total = item.parts_num * planned_production;
        });
        const arr = [];
        bom_sub.forEach((item) => arr.push(item.total));

        let fill_bom_sub = row.bomRawSourceInner.fill_bom_sub;
        fill_bom_sub.forEach((item, index) => {
          let total = arr[index];
          item.total = total;
          item.execute_list.forEach((it, idx) => {
            if (idx === 0) {
              it.num = total;
            } else {
              it.num = 0;
            }
          });
          if (!item?.supplyList) item.supplyList = item.execute_list;
          item.supplyList.forEach((itS, idxS) => {
            if (idxS === 0) {
              itS.num = total;
            } else {
              itS.num = 0;
            }
          });
        });
        console.log(row);
        console.log(this.generateList);
        this.transBomCustomList();
        return;
      }

      // 新增  请求bom详情 分配执行单位
      if (!row?.bomRawSourceInner) {
        const data = {
          id: row.bom_id || "",
        };
        this.fetchBomDetail(data, row.planned_production, index, "type");
      }
      console.log(this.generateList);
    },
    handleClick() {
      console.log(this.generateList);
    },
    bomConfirm(data) {
      console.log(data);

      const { bom_id, id } = this.currentProductSkuObj;
      console.log(bom_id);
      let key, val;
      if (id === 0) {
        key = "bom_id";
        val = bom_id;
      } else {
        key = "id";
        val = id;
      }
      this.bomVisible = false;
      for (let i = 0; i < this.generateList.length; i++) {
        if (this.generateList[i][key] === val) {
          // this.generateList[i].bom_sub = data;
          // 保存重新点击显示之前操作的数据
          // this.$set(this.generateList[i].bomRawSourceInner, "fill_bom_sub", data);
          this.generateList[i].bomRawSourceInner.fill_bom_sub = data;
          this.generateList[i].hasFillDetail = true;
          break;
        }
      }
      console.log(this.generateList);
      // debugger;
      this.transBomCustomList();
    },
    toBom(scope) {
      console.log(scope.$index);
      let index = scope.$index;
      this.currentIndex = index;
      let row = scope.row;
      if (!row.planned_production || row.planned_production < 1) {
        this.$message.warning(
          "请输入该规格成品计划生产数量，否则无法分配执行单位！"
        );
        return;
      }
      console.log(row);

      this.currentProductSkuObj = row;

      // 编辑 或已绑定数据
      console.log(row);
      // || row?.bom_sub
      if (row.id > 0) {
        // const obj = { ...row }

        // 已屏蔽代码
        // if (!obj?.bom_sub) obj.bom_sub = row.bom_list

        // let bomRawSourceInner = { ...row }
        // if (!obj?.bomRawSourceInner) {
        //   bomRawSourceInner.bom_sub = row.bom_list
        //   bomRawSourceInner.fill_bom_sub = row.bom_list
        //   this.bomRawSource = bomRawSourceInner
        // }

        // console.log(row.bom_list)
        // console.log(this.generateList)
        // if (!this.generateList[index]?.bomRawSourceInner) {
        //   this.generateList[index].bomRawSourceInner = bomRawSourceInner
        // }

        this.bomRawSource = row;
        this.bomVisible = true;
        return;
      }
      console.log(row);
      // debugger
      if (row?.bomRawSourceInner?.fill_bom_sub) {
        this.bomRawSource = row.bomRawSourceInner;
        // debugger;
        this.bomVisible = true;
        return;
      }
      const data = {
        id: row.bom_id || "",
      };
      this.fetchBomDetail(data, row.planned_production, index);
    },
    async fetchSupply(subData) {
      let materialChooseSupplyList = [];
      try {
        let arr = [];
        subData.forEach((item) => {
          const { material_id } = item;
          const params = {
            material_id,
            page: 1,
            num: 9999,
          };
          arr.push(getSupplierBomList(params));
        });
        let that = this;
        await Promise.all(arr).then((res) => {
          // console.log(res)
          // console.log(source)
          // debugger;
          subData.forEach((item, index) => {
            // 供应商数据处理
            const list = res[index].list;
            list.forEach((it) => {
              it.num = 0;
            });
            list[0].num = item.total;

            // execute_list 默认赋值
            let dataList = [];
            list.forEach((item) =>
              dataList.push({
                id: 0,
                supplier_id: item.id,
                num: item.num,
              })
            );
            const temp = {
              id: 0,
              bom_sub_id: item.id,
              material_id: item.material_id,
              total: item.total,
              supplyList: list,
              execute_list: dataList,
            };
            // const key = item.id
            // debugger;
            materialChooseSupplyList.push(temp);
            // that.materialChooseSupplyList[key] = temp;
          });
        });
      } catch (err) {}
      // 类似调用handleConfirm 保存数据到 this.generateList
      // debugger;
      this.bomConfirm(materialChooseSupplyList);
    },
    async fetchBomDetail(params, planned_production, index) {
      const res = await getBomDetail(params);
      if (res?.status === 1) {
        const data = res?.data || {};
        if (data.bom_sub.length > 0) {
          data.bom_sub.forEach((item) => {
            item.total = item.parts_num * planned_production;
          });
        }
        this.$set(this.generateList[index], "bomRawSourceInner", data);
        const subData = data.bom_sub;
        this.fetchSupply(subData);
        // this.bomRawSource = data
        // this.$set(this.generateList[index], 'bomRawSourceInner', data)

        // this.bomVisible = true
      }
    },
    handleChange(val) {
      this.useChecked = val;
      if (val) {
        this.hasBindOrder = false;
        this.bindOrderObj = {};
        this.dataForm.order_name = "";
      }
    },
    async fetchOrderDetail(data) {
      const res = await getOrderDetail(data);
      if (res?.status === 1) {
        this.orderProductData = res?.data?.order_sub || [];
        console.log(res?.data?.order_sub);
        // debugger;
      }
    },
    handleTestTasks() {
      this.$refs.choose.blur();

      this.orderVisible = true;
    },
    calcTotal() {
      // if (this.generateList.length < 1) return;
      this.tipTotal = this.generateList.reduce((pre, cur) => {
        return pre + Number(cur.planned_production);
      }, 0);
    },
    calcCustomTotal() {
      // if (this.tableData.length < 1) return;
      this.customTotal = this.tableData.reduce((pre, cur) => {
        return pre + Number(cur.num);
      }, 0);
    },
    handleSelectionChange(val) {
      this.subChooseInfo = val;
    },
    deleteTargetIds() {
      let that = this;
      let arr = [];
      // 删除添加数据
      this.subChooseInfo.forEach((item) => {
        if (item.id === 0) {
          arr = that.generateList.filter(
            (it) => it.product_sku_id !== item.product_sku_id
          );
          that.generateList = arr;
        }
      });
      this.transBomCustomList();
    },
    batchDelete() {
      if (this.subChooseInfo.length < 1) {
        this.$message.warning("请选择您需要移除的数据！");
        return;
      }
      // 删除本地添加数据
      this.deleteTargetIds();
      let that = this;

      if (!that.isAdd) {
        // 删除在线数据
        const temp = this.subChooseInfo.filter((item) => item.id !== 0);
        if (temp.length < 1) return;
        let info = [];
        temp.forEach((item) => info.push(item.id));
        const params = {
          production_id: this.dataForm.id,
          ids: info,
        };
        that
          .$confirm(
            "移除数据中有在线子订单数据，此操作将删除已选择数据, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
          .then(async () => {
            const res = await prodSubRemove(params);
            if (res?.status === 1) {
              this.$message.success(res?.msg || "");
              let wrapper = [];
              info.forEach((item) => {
                wrapper = that.generateList.filter((it) => it.id !== item);
                that.generateList = wrapper;
              });
              console.log(that.generateList);
              this.transBomCustomList();
            }
          })
          .catch(() => {});
      }
    },
    handleDelete(row) {
      const { id, production_id, product_sku_id } = row;
      let arr = [];
      if (this.isAdd || id === 0) {
        console.log(row);

        arr = this.generateList.filter(
          (item) => item.product_sku_id !== product_sku_id
        );
        this.generateList = arr;
        this.transBomCustomList();
      } else {
        this.$confirm(
          "此数据为在线数据，此操作将删除该条数据, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            const res = await prodSubRemove({ production_id, ids: [id] });
            if (res?.status === 1) {
              this.$message.success(res?.msg || "");
              arr = this.generateList.filter((item) => item.id !== id);
              this.generateList = arr;
              this.transBomCustomList();
            }
          })
          .catch(() => {});
      }
    },
    orderProductConfirm(row) {
      this.fitConfirm(row);
    },
    fitConfirm(row) {
      row.forEach((item) => {
        item.principal = null;
        item.planned_production = null;
        item.plan_start = null;
        item.plan_end = null;
        item.hasFillDetail = false;
        item.bom_list = [];
      });
      console.log(this.generateList);
      // debugger;
      this.generateList = [...this.generateList, ...row];
      console.log(this.generateList);
    },
    orderConfirm(row) {
      this.dataForm.order_name = row.name;
      this.bindOrderObj = row;
      this.hasBindOrder = true;
      this.generateList = [];
      const params = {
        id: row.id,
      };
      this.fetchOrderDetail(params);
    },
    handleClose() {
      this.addOrUpdateVisible = false;
    },
    handleBomClose() {
      this.bomVisible = false;
    },

    orderProductClose() {
      this.productOrderVisible = false;
    },

    handleOrderClose() {
      this.orderVisible = false;
    },
    handleAdd() {
      console.log(this.hasBindOrder);
      if (!this.hasBindOrder) {
        this.addOrUpdateVisible = true;
        this.productOrderVisible = false;
      } else {
        this.productOrderVisible = true;
        this.addOrUpdateVisible = false;
      }
    },
    async fetchDetail(id) {
      const params = {
        id,
      };
      const res = await getProductionDetail(params);
      if (res?.status === 1) {
        const data = res?.data || {};
        const { production_sub, order_id, ...info } = data;
        this.dataForm = info;
        production_sub.forEach((item) => {
          item.bomRawSourceInner = item;
          item.bomRawSourceInner.bom_sub = item.bom_list;
          item.bomRawSourceInner.fill_bom_sub = item.bom_list;
          item.hasFillDetail = true;
        });
        this.generateList = production_sub;
        this.oldGenerateList = production_sub;
        if (order_id) {
          this.hasBindOrder = true;
          this.dataForm.order_id = order_id;
          const params = {
            id: order_id,
          };
          this.fetchOrderDetail(params);
        } else {
          this.hasBindOrder = false;
        }
        this.transBomCustomList();
      }
    },
    goBack() {
      this.$router.go(-1);
    },

    submitJudge(list) {
      console.log(list);
      // 计划生产数量是否填写
      let isPassPlanProduction = true;
      // bom_list 供应商是否已绑定
      let isBomBind = true;
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        // 计划生产数量未填写
        if (!item.planned_production) {
          isPassPlanProduction = false;
          break;
        }
        // item.bom_sub
        if (!item?.bomRawSourceInner?.fill_bom_sub) {
          isBomBind = false;
          break;
        }
        if (item.bomRawSourceInner.fill_bom_sub.length < 1) {
          isBomBind = false;
          break;
        }
      }
      return {
        isPassPlanProduction,
        isBomBind,
      };
    },

    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate(async (valid) => {
          if (!valid) {
            return false;
          }

          // const { id, plan_end, plan_start, planned_production, product_id, product_sku_id, product_name, sku_name, principal } = this.dataForm
          // params.id = id
          // params.plan_end = plan_end
          // params.plan_start = plan_start
          // params.planned_production = planned_production
          // params.product_id = product_id
          // params.product_name = product_name
          // params.product_sku_id = product_sku_id
          // params.product_sku_name = sku_name
          // params.principal = principal

          // if (!this.hasBindOrder) {
          //   delete this.dataForm.order_id
          //   delete this.dataForm.order_name
          // }

          const params = { ...this.dataForm };
          params.id = this.dataForm.id ? this.dataForm.id : 0;
          // if (!this.hasBindOrder) {
          const { isPassPlanProduction, isBomBind } = this.submitJudge(
            this.generateList
          );
          // 请输入该规格成品计划生产数量，否则无法分配执行单位！
          if (!isPassPlanProduction) {
            this.$message.warning("计划生产数量不能为空，请确认后提交！");
            return;
          }
          if (!isBomBind) {
            this.$message.warning(
              "执行单位未分配，请查看相应规格BOM明细，绑定执行单位！"
            );
            return;
          }
          const arr = [];
          console.log(this.generateList);
          // debugger;
          this.generateList.forEach((item) => {
            // 需区分新增还是编辑 item.id === 0 新增成品

            let submitData = [];
            if (item.id === 0) {
              // 新增成品
              // const {
              //   supplyList,
              //   ...otherInfo
              // } = item.bomRawSourceInner.fill_bom_sub
              const tempList = _.cloneDeep(item?.bomRawSourceInner?.fill_bom_sub || [])
              tempList.forEach(
                (item) => delete item?.supplyList
              );
              submitData = tempList;
            } else {
              // 编辑成品
              if (item.bomRawSourceInner.fill_bom_sub.length > 0) {
                let list = item.bomRawSourceInner.fill_bom_sub;
                list.forEach((item) => {
                  let obj = {};
                  obj.bom_sub_id = item.bom_sub_id;
                  obj.id = item.id;
                  obj.material_id = item.material_id;
                  obj.total = item.total;
                  let execArr = [];
                  item.execute_list.forEach((it) => {
                    execArr.push({
                      id: it.id,
                      supplier_id: it.supplier_id,
                      num: it.num,
                    });
                  });
                  obj.execute_list = execArr;
                  submitData.push(obj)
                });
              }
            }

            console.log(submitData);
            // item.bomRawSourceInner.fill_bom_sub.forEach((it) => {
            //   delete it.supplyList;
            // });
            arr.push({
              id: item?.id || 0,
              // id: 0,
              product_id: item.product_id,
              product_name: item.product_name,
              product_sku_id: item.product_sku_id,
              product_sku_name: item.sku_name,

              // 订单才有
              sale_num: item?.sale_num || 0,
              delivery_date: item?.delivery_date || "",
              planned_production: item.planned_production || 0,
              principal: item.principal,
              plan_end: item.plan_end,
              plan_start: item.plan_start,
              // product_sku_name: item.product_sku_name,
              // principal: item.principal,
              bom_list: submitData,
            });
          });
          params.production_sub = arr;
          console.log(arr)
          // debugger
          // return
          if (this.hasBindOrder && this.isAdd)
            params.order_id = this.bindOrderObj?.id || 0;
          console.log(this.bindOrderObj);
          if (this.hasBindOrder) {
            console.log(this.bindOrderObj);
          }
          console.log(params);
          // debugger;
          // return;
          const res = await addProduction(params);
          if (res?.status === 1) {
            this.$message.success(res?.msg || "操作成功");
            this.$refs["dataForm"].resetFields();
            this.$router.go(-1);
          }
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
  // watch: {
  //   'dataForm.type' (val) {
  //     this.$refs['dataForm'].clearValidate()
  //   }
  // },
};
</script>

<style lang="scss" scoped>
.add-wrapper {
  background: #fff;
  padding: 20px;
  ::v-deep .el-page-header__title {
    font-size: 12px;
  }

  ::v-deep .el-page-header__content {
    font-size: 12px;
  }
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  .form-wrapper {
    ::v-deep .el-select {
      width: 100%;
    }

    .top-form {
      width: 50%;
      margin-top: 36px;

      .picDes {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
        line-height: 18px;
      }
    }
    .size-form {
      ::v-deep .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: auto;
      }
    }
  }
}
</style>
